	$(document).bind("mobileinit", function() {
		//宣告JQM全域屬性
		$.mobile.touchOverflowEnabled = true;
		$.mobile.allowCrossDomainPages = true;
		$.support.cors = true;
		$.mobile.phonegapNavigationEnabled = true;
		$.mobile.defaultPageTransition="none"
		//建立Web DB	
		
		//$.mobile.db = openDatabase("YuanshanMapDB","1.0","Store Tour Map Data",2*1024*1024);
	});
	
	

	$(document).bind('pageinit',function() {
				
				$.mobile.showPageLoadingMsg();
				
				$('.flexslider').flexslider({
					animation : "fade",
					controlNav : true, //Boolean: Create navigation for paging control of each clide? Note: Leave true for manualControls usage
					directionNav : true, //Boolean: Create navigation for previous/next navigation? (true/false)
					pauseOnAction: true
				});
				
				$.getJSON("http://yuanshan.17high.com.tw/API/About.asp",
						function(json) {
							for ( var i = 0; i < json.length; i++) {
								$("#description_home" + i).html(
										(json[i]['Msg']));
							}

				});
				
				//store start
				$.getJSON("http://yuanshan.17high.com.tw/API/stores.asp",
						function(json) {
							$.mobile.db = openDatabase("YuanshanMapDB","1.0","Store Tour Map Data",2*1024*1024);
							$.mobile.db.transaction (function (t) 
						    {
								console.log("Create store DB");
								t.executeSql("CREATE TABLE IF NOT EXISTS map_store_data(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,Zone TEXT,ZoneLoc TEXT,StoresClass_Id INTEGER,StoresClass_No TEXT,Stores_Id INTEGER,Stores_No TEXT,Stores_Name TEXT,Stores_LatitudeLongitude TEXT,Stores_Address TEXT,Stores_Tel TEXT,Stores_Mobile TEXT,Stores_Msg TEXT,Stores_Img TEXT,Stores_Vr  TEXT,Stores_CreateDateTime TEXT,Stores_EditDateTime TEXT)");
								t.executeSql("DELETE FROM map_store_data");
							});//create db end
								
							$.each(json,function(i,data){
							    var Zone = data.Name;
								var ZoneLoc = data.LatitudeLongitude;			
								 $.each(data.Report,function(store,storeData){
								  		var StoresClass_Id = storeData.StoresClass_Id;
										var StoresClass_No = storeData.StoresClass_No;
										var Stores_Id = storeData.Stores_Id;
										var Stores_No = storeData.Stores_No;
										var Stores_Name = storeData.Stores_Name;
										var Stores_LatitudeLongitude = storeData.Stores_LatitudeLongitude;
										var Stores_Address = storeData.Stores_Address;
										var Stores_Tel = storeData.Stores_Tel;
										var Stores_Mobile = storeData.Stores_Mobile;
										var Stores_Msg = storeData.Stores_Msg;
										var Stores_Img = storeData.Stores_Img;
										var Stores_Vr = storeData.Stores_Vr;
										var Stores_CreateDateTime = storeData.Stores_CreateDateTime;
										var Stores_EditDateTime = storeData.Stores_EditDateTime;
										
										 $.mobile.db.transaction (function (t) 
										  {
										    	
										        var sqlStores = "INSERT INTO map_store_data (Zone,ZoneLoc, StoresClass_Id,StoresClass_No,"
										        	+"Stores_Id,Stores_No,Stores_Name,"
										        	+"Stores_LatitudeLongitude,Stores_Address,Stores_Tel,Stores_Mobile,Stores_Msg,"
										        	+"Stores_Img,Stores_Vr,Stores_CreateDateTime,"
										        	+"Stores_EditDateTime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
												t.executeSql (sqlStores, [Zone, ZoneLoc,StoresClass_Id,StoresClass_No,
										        	Stores_Id,Stores_No,Stores_Name,
										        	Stores_LatitudeLongitude,Stores_Address,Stores_Tel,Stores_Mobile,Stores_Msg,
										        	Stores_Img,Stores_Vr,Stores_CreateDateTime,
										        	Stores_EditDateTime]);							      
										      
										  });
								  
								  });


						    });
							
							
				});//store end


				$.getJSON("http://yuanshan.17high.com.tw/API/Vr.asp",
						function(json) {
							$.mobile.db = openDatabase("YuanshanMapDB","1.0","Store Tour Map Data",2*1024*1024);
							$.mobile.db.transaction (function (t) 
						    {
								console.log("Create Tour DB");
								t.executeSql("CREATE TABLE IF NOT EXISTS map_tour_data(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,Zone TEXT,ZoneLoc TEXT,AttractionsGroup_Id INTEGER,AttractionsGroup_No TEXT,AttractionsGroup_Name TEXT,AttractionsGroup_LatitudeLongitude TEXT,AttractionsGroup_Address TEXT,AttractionsGroup_Msg TEXT,AttractionsGroup_Traffic TEXT,AttractionsGroup_Img TEXT,AttractionsGroup_Vr TEXT,AttractionsGroup_CreateDateTime TEXT,AttractionsGroup_EditDateTime TEXT,AttractionsItem_Name TEXT,AttractionsItem_VrImg TEXT,AttractionsItem_Vr TEXT)");
								t.executeSql("DELETE FROM map_tour_data");
																
						    });
							
							
							console.log("Update Tour DB");
							
							
							
							//Insert DB for Tours
							$.each(json,function(i,data){
								var Zone = data.Name;
								var ZoneLoc = data.LatitudeLongitude;
								
							    {								  
								   $.each(data.Report,function(tour,tourData){
									  
								      var AttractionsGroup_Id = tourData.AttractionsGroup_ID;
								      var AttractionsGroup_No = tourData.AttractionsGroup_No;							  
								      var AttractionsGroup_Name = tourData.AttractionsGroup_Name;
								      var AttractionsGroup_LatitudeLongitude = tourData.AttractionsGroup_LatitudeLongitude;
								      var AttractionsGroup_Address = tourData.AttractionsGroup_Address;
								      var AttractionsGroup_Msg = tourData.AttractionsGroup_Msg;
								      var AttractionsGroup_Traffic = tourData.AttractionsGroup_Traffic;
								      var AttractionsGroup_Img = tourData.AttractionsGroup_Img;
								      var AttractionsGroup_Vr = tourData.AttractionsGroup_Vr;
								      var AttractionsGroup_CreateDateTime = tourData.AttractionsGroup_CreateDateTime;
								      var AttractionsGroup_EditDateTime = tourData.AttractionsGroup_EditDateTime;								 
								      
								      if(tourData['VrGroup']!=""){
								    	  $.each(tourData.VrGroup,function(vr,vrData){
										      var AttractionsItem_Name = vrData.AttractionsItem_Name;
										      var AttractionsItem_VrImg = vrData.AttractionsItem_Img;
										      //console.log("AttractionsItem_VrImg = "+AttractionsItem_VrImg);
										      var AttractionsItem_Vr = vrData.AttractionsItem_Vr;
										    
										      $.mobile.db.transaction (function (t) 
										      {
										    	
										        var sqlTour = "INSERT INTO map_tour_data (Zone,ZoneLoc,AttractionsGroup_Id,AttractionsGroup_No,"
										        	+"AttractionsGroup_Name,AttractionsGroup_LatitudeLongitude,AttractionsGroup_Address,"
										        	+"AttractionsGroup_Msg,AttractionsGroup_Traffic,AttractionsGroup_Img,AttractionsGroup_Vr,"
										        	+"AttractionsGroup_CreateDateTime,AttractionsGroup_EditDateTime,AttractionsItem_Name,"
										        	+"AttractionsItem_VrImg,AttractionsItem_Vr) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
										        t.executeSql (sqlTour, [Zone, ZoneLoc,AttractionsGroup_Id,AttractionsGroup_No,AttractionsGroup_Name,AttractionsGroup_LatitudeLongitude,AttractionsGroup_Address,
										                                      AttractionsGroup_Msg,AttractionsGroup_Traffic,AttractionsGroup_Img,AttractionsGroup_Vr,AttractionsGroup_CreateDateTime,
										                                      AttractionsGroup_EditDateTime,AttractionsItem_Name,AttractionsItem_VrImg,AttractionsItem_Vr]);							      
										      });
								      });
								      }else{
								    	  $.mobile.db.transaction (function (t) 
										  {											    	
											        var sqlTourNoData = "INSERT INTO map_tour_data (Zone,ZoneLoc, AttractionsGroup_Id,AttractionsGroup_No,"
											        	+"AttractionsGroup_Name,AttractionsGroup_LatitudeLongitude,AttractionsGroup_Address,"
											        	+"AttractionsGroup_Msg,AttractionsGroup_Traffic,AttractionsGroup_Img,AttractionsGroup_Vr,"
											        	+"AttractionsGroup_CreateDateTime,AttractionsGroup_EditDateTime,AttractionsItem_Name,"
											        	+"AttractionsItem_VrImg,AttractionsItem_Vr) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
											        t.executeSql (sqlTourNoData, [Zone, ZoneLoc,AttractionsGroup_Id,AttractionsGroup_No,AttractionsGroup_Name,AttractionsGroup_LatitudeLongitude,AttractionsGroup_Address,
											                                      AttractionsGroup_Msg,AttractionsGroup_Traffic,AttractionsGroup_Img,AttractionsGroup_Vr,AttractionsGroup_CreateDateTime,
											                                      AttractionsGroup_EditDateTime,"","",""]);							      
										  });
								      }
								  });
							   }
							
							});
							 									
					    }				
				);
				
				$.mobile.hidePageLoadingMsg();
				
				
			});
						
		    var curGeoPoint = { 'center': '25.0336,121.56482', 'zoom': 14 };
			
			var isTour = true;
			var isJala = false;
			var isDala = false;
			var isHala = false;
           
	        $("#jala_map").live('pageinit', function(e){
	        	   if(navigator.geolocation){
	        		   
				   	   isJala=true;
				       isDala=false;
					   isHala=false;     		   				
					   navigator.geolocation.getCurrentPosition(displayLocation_map, displayError);
					   $("#loc_tour").bind('click',function(e){
						   		isTour = true;
					   			navigator.geolocation.getCurrentPosition(displayLocation_map, displayError);
								e.preventDefault();					   	
					   });
					   $("#loc_store").bind('click',function(e){
						        isTour = false;
					   			navigator.geolocation.getCurrentPosition(displayLocation_store, displayError);					   	
								e.preventDefault();
					   });
	        	   }
	        });
			
			$("#dala_map").live('pageinit', function(e){
 				       isJala=false;
				       isDala=true;
					   isHala=false;
					   navigator.geolocation.getCurrentPosition(displayLocation_map, displayError);
	        	   if(navigator.geolocation){	        		   					   
					    $("#loc_tour").bind('click',function(e){
						   		isTour = true;
					   			navigator.geolocation.getCurrentPosition(displayLocation_map, displayError);
								e.preventDefault();					   	
					   });
					   $("#loc_store").bind('click',function(e){
						        isTour = false;
					   			navigator.geolocation.getCurrentPosition(displayLocation_store, displayError);					   	
								e.preventDefault();
					   });
	        	   }
	        });
			
			$("#hala_map").live('pageinit', function(e){
				     isJala=false;
				     isDala=false;
					 isHala=true;
					 navigator.geolocation.getCurrentPosition(displayLocation_map, displayError);
	        	     $("#loc_tour").bind('click',function(e){
						   		isTour = true;
					   			navigator.geolocation.getCurrentPosition(displayLocation_map, displayError);
								e.preventDefault();					   	
					      });
					 $("#loc_store").bind('click',function(e){
						        isTour = false;
					   			navigator.geolocation.getCurrentPosition(displayLocation_store, displayError);					   	
								e.preventDefault();
					  });
	        });
			$("#jala_tour_list").live('pageinit', function(e){
				getToursList(0);
			});
			$("#jala_store_list").live('pageinit', function(e){
				getStoressList(0);
			});
			
			
			$("#info").live('pageinit', function(e){
				getInfo();				
			});

			
			//Get Info
			function getInfo(){
				var listInfo = $("#listInfo");
				var items=[];
			   $.getJSON("http://yuanshan.17high.com.tw/API/news.asp",
					function(json) {
						$.each(json,function(i,data){
							if(data.Name=='Jala'){
								$.each(data.Report,function(j,datainfo){
									console.log("getInfo = " + datainfo.News_Title);
									items.push("<li><img src='images/logo1.png'><h3>枕頭山休閒農業區</h3><p>日期:</p>"
									+"<p>標題:'"+datainfo.News_Title+"'</p></li>");
								});
								
							}else if(data.Name=='Dala'){
								$.each(data.Report,function(j,datainfo){
									items.push("<li><img src='images/logo2.png'><h3>大湖底休閒農業區</h3><p>日期:</p>"
									+"<p>標題:'"+datainfo.News_Title+"'</p></li>");
								});
								
							}else if(data.Name=='Hala'){
								$.each(data.Report,function(j,datainfo){
									items.push("<li><img src='images/logo3.png'><h3>横山頭休閒農業區</h3><p>日期:</p>"
									+"<p>標題:'"+datainfo.News_Title+"'</p></li>");
								});
								
							}
					
					});
					
					
					listInfo.html(items.join('\n'));
					listInfo.listview("refresh");

				});
			}
			
		//	$("#list0").bind('click',function(e){
				
		//	});
			
			
			function displayLocation_map(pos){

				console.log("isTour=" + isTour);
				console.log("isJala=" + isJala);
				console.log("isDala=" + isDala);
				console.log("isHala=" + isHala);
   	        	//alert("longitude="+format(pos.coords.longitude,2)+",latitude="+format(pos.coords.latitude,2));
				if(isJala)
				    showMap(0,0,pos.coords);
				else if(isDala)
					showMap(1,0,pos.coords);
				else if(isHala)
					showMap(2,0,pos.coords);
   	        }
			
			function displayLocation_store(pos){
				console.log("isTour=" + isTour);
				console.log("isJala=" + isJala);
				console.log("isDala=" + isDala);
				console.log("isHala=" + isHala);
				if(isJala)
				    showMap(0,1,pos.coords);
				else if(isDala)
					showMap(1,1,pos.coords);
				else if(isHala)
					showMap(2,1,pos.coords);
			}
				
	        
			function displayError(error){
			switch(error.code){
					case error.TIMEOUT :
						alert( " 連接超時，請重試 " );
						break;
					case error.PERMISSION_DENIED :
						alert( " 您拒絕了使用位置共享服務，查詢已取消 " );
						break;
					case error.POSITION_UNAVAILABLE : 
						alert( " 親愛的火星網友，非常抱歉，我們暫時無法為您所在的星球提供位置服務 " );
						break;
				}
			}
			

	        
	        function format(number,decplaces){
	        	var val = eval(number);
	        	var str=""+Math.round(val * Math.pow(10,decplaces));
	        	while(str.length <=decplaces){
	        		str = "0"+str;
	        	}
	        	
	        	var decpoint = str.length-decplaces;
	        	return str.substring(0,decpoint) + "."+str.substring(decpoint,str.length);
	        }
	        
	        function showMap(mapID,mapType,coords){
	        	 var latlng = new google.maps.LatLng(coords.latitude, coords.longitude);
	        	 var mapOpts = {
	        			 zoom:13,
	        			 center:latlng,
	        			 mapTypeId: google.maps.MapTypeId.ROADMAP,
	        			 navigationControl: false,
	        			 mapTypeControl: false
	        	 };
	        	 var mapDiv = document.getElementById("mapDiv"+mapID);
				 var map = new google.maps.Map(mapDiv,mapOpts);
				 map.setCenter(latlng);
					var marker = new google.maps.Marker({
						map: map,
						position: latlng
					});
	        }
			
			
			
			
			function getToursList(tour_id){
				var listTours = $("#lvTours");
				var items=[];
				//alert($.mobile.db);
				$.mobile.db.transaction (function (t) {
					var toursql = "SELECT AttractionsGroup_No,AttractionsGroup_Name,AttractionsGroup_LatitudeLongitude,AttractionsGroup_Address,AttractionsGroup_Img from map_tour_data where Zone='Jala' group by AttractionsGroup_Name";
					t.executeSql(toursql,[],function(t, result){
						  var i, len=result.rows.length,row;
						  //alert("data len="+len);
						  if(len>0){
						  	 for(i=0;i<len;i+=1){
							 	row = result.rows.item(i);
							 	//alert(row.AttractionsGroup_Img);
								items.push("<li><a href='#displayTourDetail' data-trnote='"+row.AttractionsGroup_No +"'><img src='"+row.AttractionsGroup_Img+"'><h3>名稱:"+row.AttractionsGroup_Name+"</h3><p>地址:"+row.AttractionsGroup_Address+"</p></a></li>");
							 }
							 listTours.html(items.join('\n'));
							 listTours.listview("refresh");
							 
							 $("a",listTours).bind('click',function(e){
							 	getTourDetails($(this).attr("data-trnote"));
							 });
						  }
					});
				
				});
				
				
			}
			function getStoressList(store_id){
				var listStores = $("#lvStores");
				var items=[];
				var zone;
				if(store_id==0)
					zone="Jala"
				else if(store_id==1)
					zone="Dala"
				else if(store_id==2)
					zone="Hala"
				//alert($.mobile.db);
				$.mobile.db.transaction (function (t) {
					var storesql = "SELECT Stores_Id,Stores_No,Stores_Name,Stores_LatitudeLongitude,Stores_Address,Stores_Tel,Stores_Mobile,Stores_Msg,Stores_Img from map_store_data where Zone='"+zone+"'";
					t.executeSql(storesql,[],function(t, result){
						  var i, len=result.rows.length,row;
						  alert("store data len="+len);
						  if(len>0){
						  	 for(i=0;i<len;i+=1){
							 	row = result.rows.item(i);
							 	//alert(row.AttractionsGroup_Img);
								items.push("<li><a href='#displayStoresDetail' data-trnote='"+row.Stores_No +"'><img src='"+row.Stores_Img+"'><h3>名稱:"+row.Stores_Name+"</h3><p>地址:"+row.Stores_Address+"</p></a></li>");
							 }
						  	listStores.html(items.join('\n'));
						  	listStores.listview("refresh");
							 
							 $("a",listStores).bind('click',function(e){
							 	getStoreDetails($(this).attr("data-trnote"));
							 });
						  }
					});
				
				});
				
				
			}
			
			
			function getTourDetails(No){
				var showName = $("#showName");
				var showImg = $("#showImg");
				var showTourContent = $("#showTourContent");
				var showTourWay = $("#showTourWay");
				var items=[];
				//alert($.mobile.db);
				$.mobile.db.transaction (function (t){
				var detailssql = "SELECT Stores_Id,Stores_No,Stores_Name,Stores_LatitudeLongitude,Stores_Address,Stores_Tel,Stores_Mobile,Stores_Msg,Stores_Img from map_store_data where Stores_No=" + No;
					t.executeSql(detailssql,[],function(t, result){
						 var len=result.rows.length,row;
						 if(len > 0){
						 	row = result.rows.item(0);
							showName.html("<h2>"+row.Stores_Name+"</h2>");
							showImg.html("<img src='"+row.Stores_Img+"'>");
							showTourWay.html("<h3>店家簡介</h3><p>"+row.Stores_Msg+"</p>");
							
							$("#displayVR").bind('click',function(e){
							 	getTourVR(No);
							 });
							//
						 }
					});		
				});
			}
			
			function getStoreDetails(No){
				var showName = $("#showName");
				var showImg = $("#showImg");
				var showStoreContact = $("#showStoreContact");
				var showStoreMsg = $("#showStoreMsg");
				var items=[];
				//alert($.mobile.db);
				$.mobile.db.transaction (function (t){
				var detailssql = "SELECT AttractionsGroup_No,AttractionsGroup_Name,AttractionsGroup_LatitudeLongitude,AttractionsGroup_Msg ,AttractionsGroup_Traffic,AttractionsGroup_Img from map_tour_data where AttractionsGroup_No='"+No+"' group by AttractionsGroup_Name";
					t.executeSql(detailssql,[],function(t, result){
						 var len=result.rows.length,row;
						 if(len > 0){
						 	row = result.rows.item(0);
							showName.html("<h2>"+row.AttractionsGroup_Name+"</h2>");
							showImg.html("<img src='"+row.AttractionsGroup_Img+"'>");
							showTourContent.replaceWith('<div id="showStoresContent" data-role="collapsible" data-collapsed="true">' + "<h3>景點內容</h3><p>"+row.AttractionsGroup_Msg+"</p>"+ '</div>');
							$('#collapsibleSet').find('div[data-role=collapsible]').collapsible({refresh:true});
							showTourWay.replaceWith('<div id="showTourContent" data-role="collapsible" data-collapsed="true">' + "<h3>交通資訊</h3><p>"+row.AttractionsGroup_Traffic+"</p>"+ '</div>');
							
							$('#collapsibleSet').find('div[data-role=collapsible]').collapsible({refresh:true});
							$("#displayVR").bind('click',function(e){
							 	getTourVR(No);
							 });
							//
						 }
					});		
				});
			}
			
			
			$("#passport").live('pageinit',function(e){
				
				$('a#qrscan').live('click', function(e) {
				    window.plugins.barcodeScanner.scan(
       		 	function(result) {
						alert("Scanned Code: " + result.text 
					+ ". Format: " + result.format
					+ ". Cancelled: " + result.cancelled);
   		 		}, function(error) {
        			alert("Scan failed: " + error);
   				 });
    			});
				
				 
							
			});
			
			function getTourVR(No){
			   console.log(No);
			}
			
			
		
			
			